<template>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      :showCancel="true"
      @close="dialogConfig.show = false"
      width="800px"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="80px"
        @submit.prevent
      >

        <!-- 新增用户搜索 -->
      <el-form-item label="选择用户" prop="userId">
        <el-autocomplete
          v-model="searchKey"
          :fetch-suggestions="searchUser"
          placeholder="输入用户名搜索"
          @select="handleUserSelect"
          clearable
        >
          <template #default="{ item }">
            <span>{{ item.username }}</span>
            <span style="margin-left:15px;color:#909399">{{ item.email }}</span>
          </template>
        </el-autocomplete>
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formData.username"
          disabled
          placeholder="选择用户后自动填充"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="formData.email"
          disabled
          placeholder="选择用户后自动填充"
        />
      </el-form-item>

      <el-form-item label="处罚方式" prop="action">
        <el-select
          v-model="formData.action"
          placeholder="请选择处罚方式eg：警告 封号"
        >
          <el-option :value="0">警告</el-option>
          <el-option :value="1">封号</el-option>
      </el-select>
      </el-form-item>

      <el-form-item label="处罚原因" prop="reason">
        <el-input
          v-model="formData.reason"
          type="textarea"
          :rows="4"
          placeholder="请输入处罚原因（200字符内）"
          :maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    </Dialog>
  </template>
  <script setup>
  import { ref, reactive, getCurrentInstance, nextTick } from "vue";
  const { proxy } = getCurrentInstance();

  const api = {
    saveAccount: "/violation/add",
    searchUser:"/userInfo/loadUserList",
    getUserInfo:'/userInfo/getUserInfo'
  };

  const dialogConfig = ref({
    show: false,
    title: "新增账号",
    buttons: [
      {
        type: "primary",
        text: "确定",
        click: (e) => {
          submitForm();
        },
      },
    ],
  });

  // 扩展表单数据
  const formData = ref({
    certificateNo: "",
    specialty: [],
    introduction: ""
  })
  const formDataRef = ref();


  // 新增数据项
  const searchKey = ref("")

// 新增方法 - 用户搜索
const searchUser = async (query, cb) => {
  if (!query) return cb([])
  const result = await proxy.Request({
    url: api.searchUser,
    params: { usernameFuzzy: query,
    }
  })
  cb(result.data.list || [])
}

// 新增方法 - 用户选择
const handleUserSelect = (user) => {
  formData.value = {
    userId: user.userId,
    username: user.username,
    phone: user.phone,
    email: user.email
  }
}


  const rules = {
    action: [{ required: true, message: "请选择处罚方式" }],
    reason: [{ required: true, message: "请输入处罚原因" }],
  };

  const loadUserInfo = async (userId) => {
    const result = await proxy.Request({
      url: api.getUserInfo,
      params: {
         userId: userId,
      }
    }
  )
  if(!result){
    return;
  }
  formData.value.userId =result.data.userId;
  formData.value.username =result.data.userId;
  formData.value.email =result.data.email;
}
  const showEdit = (data) => {
    dialogConfig.value.show = true;
    nextTick(() => {
      formDataRef.value.resetFields();
      if (data.userId == null) {
        dialogConfig.value.title = "新增处罚信息";

      } else {
        dialogConfig.value.title = "修改处罚信息";
        loadUserInfo(data.userId);
        formData.value = data;
        formData.value.qualification = data.qualification.split(",");
        formData.value.specialty = data.specialty.split(",");
      }
    });
  };

  defineExpose({
    showEdit,
  });

  const emit = defineEmits(["reload"]);
  const submitForm = async () => {
    formDataRef.value.validate(async (valid) => {
      if (!valid) {
        return;
      }
      let params = {};
      Object.assign(params, formData.value);
      params.status=0;
      let result = await proxy.Request({
        url: api.saveAccount,
        params,
      });
      if (!result) {
        return;
      }
      dialogConfig.value.show = false;
      proxy.Message.success("保存成功");
      emit("reload");
    });
  };
  </script>

  <style lang="scss" scoped>
  .check-span-item {
    float: left;
    margin-right: 10px;
    line-height: 20px;
  }
  </style>
